Skip to content

perf(sampling): share one sampler between requests with equal parameters - #4376

Merged
jundot merged 3 commits into
jundot:mainfrom
AureliusClaw:pr/shared-sampler
Oct 12, 2026
Merged

jundot merged 3 commits into
jundot:mainfrom
AureliusClaw:pr/shared-sampler

Conversation

@AureliusClaw

Copy link
Copy Markdown
Contributor

Summary

When every row of a decode batch holds the same sampler object, mlx-lm's GenerationBatch._step samples the whole batch in one call (mlx_lm/generate.py: if not samplers or all(s is samplers[0] for s in samplers)). Otherwise it runs each row's sampler on a one-row slice and concatenates the results. The scheduler builds a fresh sampler per request (_build_sampler_and_processors), so a batch of B requests with identical sampling parameters always takes the per-row path. That costs B filter-and-sample chains per step (top-k, top-p, categorical over the full vocabulary: about forty graph ops and their launches per row) instead of one.

This PR adds make_shared_sampler in omlx/utils/sampling.py. It hands requests with equal (temp, top_p, min_p, min_tokens_to_keep, top_k) the same callable from a small bounded cache (256 entries, LRU), and the per-request builder uses it.

  • Correctness. The samplers are stateless closures, and their filters are row-wise. Each row of a shared call is filtered exactly as a one-row call would filter it (tested for top-k, top-p, min-p and greedy). Only the RNG stream behind the draws changes: the batch draws once instead of B times. seed keeps its existing best-effort semantics, because it already seeds the global MLX RNG.
  • XTC is never shared. Its coin flip is one draw per call, so sharing would make one flip for the whole batch.
  • Opt-out. OMLX_SHARED_SAMPLERS=0 restores one sampler per request. That is also the baseline below.

Alternatively, mlx-lm could group rows by equal sampler parameters itself. I went with the smaller change here, since omlx builds the sampler objects.

Validation

Benchmark. Mac Studio M5 Ultra, 256 GB. main cc1fdc9 + this PR, native kernels built (OMLX_WITH_CUSTOM_KERNEL=1). Qwen3.8-Flash-Next oQ4e, qwen35_oq_a8_enabled, top_k 20, prefix cache on.

  • Baseline: the same build with OMLX_SHARED_SAMPLERS=0. That is the code path on main.
  • Load: N streaming chat requests start together. They share a 2K (or 32K) system prompt and differ in the user turn; at 32K, stream i also adds i × 2K unshared tokens. Each generates 512 (32K: 768) tokens at temperature 0.7 with seed i.
  • Metric: steady aggregate decode tok/s, over the window in which every stream is decoding.
  • Runs: each arm on a fresh server, ABBA order, two runs per cell.
2K × 1 2K × 4 2K × 8 32K × 8
MTP off, per-request samplers (main) 111 / 111 239 / 238 279 / 279 194 / 189
MTP off, shared (this PR) 111 / 111 242 / 242 288 / 288 205 / 201
Lightning MTP on, per-request 208 / 208 234 / 234
Lightning MTP on, shared 210 / 212 240 / 243

That is +3 % at 8 streams for 2K and about +6 % at 32K × 8. A single stream is unchanged, as expected: one row is one call either way. TTFT and peak memory are unchanged (max TTFT 2.9–3.2 s at 2K × 8, 31.6 s at 32K × 8; footprint within 2 GB).

Tests. tests/test_shared_sampler.py (11 tests, CPU) covers:

  • sharing and key separation;
  • XTC exclusion;
  • the opt-out;
  • the cache bound;
  • row-wise equality of shared calls against one-row calls;
  • that draws stay inside each row's support;
  • that two scheduler requests with equal parameters get the same object.

The default suite (-m "not slow and not integration", same machine): main cc1fdc9 gives 17,222 passed, 659 skipped. This branch gives 17,233 passed (the 11 new tests), 659 skipped, 0 failures.

Black and Ruff are clean on the new code. The remaining Ruff findings in sampling.py and Black's on scheduler.py already exist on main.

Checklist

  • I read CONTRIBUTING.md.
  • I understand every change in this PR and can explain it in review.
  • For UI or UX changes, I attached before and after screenshots. (No UI changes.)

🤖 Generated with Claude Code

AureliusClaw and others added 3 commits October 8, 2026 19:56
mlx-lm's GenerationBatch._step samples a decode batch in one call only
when every row's sampler is the same object. The scheduler built a fresh
sampler per request, so a batch of B requests with identical parameters
ran B one-row filter-and-sample chains (top-k, top-p, categorical over
the 248K vocabulary: about forty graph ops and GPU launches per row)
and concatenated them.

make_shared_sampler hands equal (temp, top_p, min_p, min_tokens_to_keep,
top_k) the same callable from a bounded cache, and the per-request
builder uses it. The samplers are stateless; each row still draws from
its own filtered distribution (the filters are row-wise, tested equal to
one-row calls), only the RNG stream behind the draws changes. XTC is
never shared (its coin flip is one draw per call).
OMLX_SHARED_SAMPLERS=0 restores one sampler per request.

Co-authored-by: Sören Sanders <81529835+w-Teilchen@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A module-level mx.set_default_device(mx.cpu) moved every later test in the
pytest session to the CPU: test_qwen35_verify_sdpa_split then failed 7 tests
and the session segfaulted (full qwen4/mtp/scheduler suite, M5 Ultra). A
module-scoped autouse fixture now sets the CPU and restores the previous
device.

Co-authored-by: Sören Sanders <81529835+w-Teilchen@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ampler tests

Co-authored-by: Sören Sanders <81529835+w-Teilchen@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sharing the sampler lets mlx-lm sample the whole batch in one call, and each row still samples from its own distribution. Here's what I got on M5 Max with Qwen3.6-35B-A3B (temperature 1.0, top_p 0.95, top_k 20, aggregate decode throughput).

Load Shared off Shared on Change
8 streams x 2K, 512 tokens 378.6 tok/s 414.1 tok/s +9.3%
8 streams x 32K, 256 tokens 144.7 tok/s 155.8 tok/s +7.7%
Check Result
Same prompt x8 at temperature 1.0 All outputs differ
Same seed twice Identical
Greedy x8 Identical

I'll drop the OMLX_SHARED_SAMPLERS switch in a small follow-up since I keep env toggles out of production code. Thanks, LGTM, merging.

@jundot
jundot merged commit 0c6fd95 into jundot:main Oct 12, 2026
jundot added a commit that referenced this pull request Oct 12, 2026
- #4376: drop OMLX_SHARED_SAMPLERS, cache samplers with lru_cache, move tests into test_sampling.py
- #4386: read the target model_type directly
- #4408: drop the decode try/except, keep the older verify tests on their own paths
- #4442: shorten docstrings, move tests into test_turboquant.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants